<?php
/**
 * Created by PhpStorm.
 * User: linyh
 * Date: 2015/10/6
 * Time: 13:58
 */

namespace app\modules\frontend\controllers;

use app\lib\DataMessage;
use app\lib\QiniuHelper;
use Yii;
use yii\base\UserException;
use yii\helpers\Json;

// TODO 应该把发送验证码、检测验证码、图片验证码等等都放在这里
class SundryController extends BaseController {
    public $enableCsrfValidation = false;

    public function actionUploadToken($type = 'image') {
        // 这就生成了一个上传用的token
        return Json::encode(['uptoken' => QiniuHelper::backBaseApiToken($type)]);
    }

    // call back url 或者直接上传应该也没问题
    public function actionUpload() {
        $_body = file_get_contents('php://input');
        $post = json_decode($_body, true);
        $file = Yii::$app->sundry->recordFile($post);
        return DataMessage::initSuccess($file);
    }

    public function actionFetch($source_url, $filename = null, $type = 'image') {
        $ret = QiniuHelper::fetch($source_url, $filename, $type);
        if (empty($ret)) {
            throw new UserException('无法抓取');
        }
        $file = Yii::$app->sundry->recordFile($ret);
        return DataMessage::initSuccess($file);
    }
}
